﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CounterServerModel;
using System.Data;
using CounterServerModel.Authentication;

namespace SmartCounters
{
	public partial class UserDetails : System.Web.UI.Page
	{
		public static string k_UserSessionKey = "UserToUpdate";
		UserInfo m_UserToUpdate;
		UserInfo m_UserToCreate;

		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_AdminPageFilter;
			((MainTemplate)Master).ShowHeader = false;
		}

		protected void Page_Prerender(object sender, EventArgs e)
		{
			m_UserToUpdate = Session[k_UserSessionKey] as UserInfo;
			
			populatePermissionList();
			populateAccountsList();
			setFromMode();
			tbUsername.Focus();
		}

		

		private void setFromMode()
		{
			if (m_UserToUpdate != null)
			{
				btAdd.Visible = false;
				btUpdate.Visible = true;
				loadUserFormDetails(m_UserToUpdate);
			}
			else
			{
				btUpdate.Visible = true;
				btUpdate.Visible = false;
			}
		}

		private void populatePermissionList()
		{
			if (!IsPostBack)
			{
				cbPermissions.DataSource = Enum.GetNames(typeof(eUserPermissions));
				cbPermissions.DataBind();
			}
		}

		private void populateAccountsList()
		{
			InformationReader infoProvider = new InformationReader();
			DataTable accountsTable = new InformationReader().GetAccountsDataTable(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			if (!IsPostBack)
			{
				foreach (DataRow account in accountsTable.Rows)
				{
					string accountLable = account["Country"] + " " + account["City"] + " " + account["street"] + " " + account["House"] + "/" + account["Apartment"];
					cbAssociatedAccounts.Items.Add(new ListItem(accountLable, account["AccountID"].ToString()));
				}
			}
		}


		private void loadUserFormDetails(UserInfo i_UserInfo)
		{
			clearUserForm();
			hdUserID.Value = i_UserInfo.ID.ToString();
			tbUsername.Text = i_UserInfo.Username;
			tbPhone.Text = i_UserInfo.Phone;
			tbMobilePhone.Text = i_UserInfo.MobilePhone;
			tbEmail.Text = i_UserInfo.Email;
			tbPassword.Text = i_UserInfo.Password;

			foreach (ListItem permissionItem in cbPermissions.Items)
			{
				eUserPermissions permissionToSet = (eUserPermissions)Enum.Parse(typeof(eUserPermissions), permissionItem.Value);
				if ((permissionToSet & i_UserInfo.UserPermissions) == permissionToSet)
				{
					permissionItem.Selected = true;
				}
			}

			foreach (int userAccountID in i_UserInfo.AccountsAssociatedWith)
			{
				cbAssociatedAccounts.Items.FindByValue(userAccountID.ToString()).Selected = true;
			}
		}

		private void getUserInfoFromForm(ref UserInfo i_UserInfo)
		{
			String username = tbUsername.Text;
			String phone = tbPhone.Text;
			String mobilePhone = tbMobilePhone.Text;
			String email = tbEmail.Text;
			String password = tbPassword.Text;

			i_UserInfo.Username = username;
			i_UserInfo.Phone = phone;
			i_UserInfo.Email = email;
			i_UserInfo.MobilePhone = mobilePhone;
			i_UserInfo.Password = password;
			i_UserInfo.UserPermissions = getUserPermissionFromCheckBoxList();
			i_UserInfo.AccountsAssociatedWith = getUserAssociatedAccount();
		}

		private List<int> getUserAssociatedAccount()
		{
			List<int> userAssociatedAccounts = new List<int>();
			foreach (ListItem accountItem in cbAssociatedAccounts.Items)
			{
				if (accountItem.Selected)
				{
					int accountID = int.Parse(accountItem.Value);
					userAssociatedAccounts.Add(accountID);
				}
			}

			return userAssociatedAccounts;
		}

		protected void AddUser(object sender, EventArgs e)
		{
			m_UserToCreate = new UserInfo();
			getUserInfoFromForm(ref m_UserToCreate);

			InformationUpdater updateProvider = new InformationUpdater();
			updateProvider.CreateUser(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, m_UserToCreate);
			clearUserForm();
			Session[k_UserSessionKey] = null;
		}

		protected void UpdateUser(object sender, EventArgs e)
		{
			m_UserToUpdate = Session[k_UserSessionKey] as UserInfo;
			getUserInfoFromForm(ref m_UserToUpdate);

			InformationUpdater updateProvider = new InformationUpdater();
			updateProvider.UpdateUser(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, m_UserToUpdate);
			clearUserForm();
			Session[k_UserSessionKey] = null;
		}

		protected void Cancel(object sender, EventArgs e)
		{
			clearUserForm();
			Session[k_UserSessionKey] = null;

		}

		private eUserPermissions getUserPermissionFromCheckBoxList()
		{
			eUserPermissions resultPermission = eUserPermissions.None;

			foreach (ListItem permission in cbPermissions.Items)
			{
				if(permission.Selected)
				{
					eUserPermissions permissionToSet = (eUserPermissions)Enum.Parse(typeof(eUserPermissions), permission.Value);
					resultPermission |= permissionToSet;
				}
			}

			return resultPermission;
		}

		private void clearUserForm()
		{
			tbUsername.Text = "";
			tbPhone.Text = "";
			tbMobilePhone.Text = "";
			tbEmail.Text = "";
			tbPassword.Text = "";
			cbPermissions.ClearSelection();
		}

		
	}
}